<template>
  <div class="consultation">
    <h2>试卷管理</h2>
    <div class="flex-center">
      <el-button class="ml0" size="mini" type="success" @click="addPaper"
        >手动出题</el-button
      >
      <el-dropdown trigger="click" @command="addPaperAuto">
        <el-button class="ml0" size="mini" type="success"
          >自动出题<i class="el-icon-arrow-down el-icon--right"></i
        ></el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item command="1">简单</el-dropdown-item>
          <el-dropdown-item command="2">中等</el-dropdown-item>
          <el-dropdown-item command="3">困难</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <el-input
        v-model="key"
        size="mini"
        style="width: 120px"
        placeholder="关键字/词查询"
      ></el-input>
      <el-button
        class="ml0"
        size="mini"
        type="primary"
        @click="refreshTable(true)"
        >查询</el-button
      >
    </div>
    <div class="consultation-block">
      <div class="table">
        <el-table size="mini" :data="tableDataPaper" style="width: 100%">
          <el-table-column label="序号" type="index"> </el-table-column>
          <el-table-column prop="name" label="试卷名称"> </el-table-column>
          <el-table-column label="操作" width="250">
            <template slot-scope="scope">
              <el-button
                type="warning"
                size="mini"
                @click="updatePaper(scope.row)"
                >编辑</el-button
              >
              <el-button
                type="danger"
                size="mini"
                @click="deletePaper(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="pagination">
        <el-pagination
          background
          layout="prev, pager, next"
          :current-page.sync="currentPage"
          @current-change="refreshTable"
          :page-size="pageSize"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
    <el-dialog
      :title="addForm.id ? '编辑' : '新增'"
      :visible.sync="isAddVisible"
      :close-on-click-modal="false"
      width="60%"
      :before-close="handleAddClose"
    >
      <el-form
        :model="addForm"
        status-icon
        :rules="rules"
        size="mini"
        ref="addForm"
        label-width="100px"
      >
        <el-form-item label="试卷名称" prop="name">
          <el-input type="text" v-model="addForm.name"></el-input>
        </el-form-item>
      </el-form>
      <div class="table">
        <el-table
          ref="multipleTable"
          size="mini"
          :data="tableData"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column label="序号" type="index"> </el-table-column>
          <el-table-column prop="name" label="试题名称" :formatter="formatter1">
          </el-table-column>
          <el-table-column prop="score" label="分数"> </el-table-column>
          <!-- <el-table-column prop="selections" label="选项" :formatter="formatter"> </el-table-column> -->
          <el-table-column
            prop="hard"
            label="难度系数"
            :formatter="formatterHard"
          >
          </el-table-column>
          <el-table-column prop="type" label="类型"> </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isAddVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('addForm')"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <el-dialog
      title="自动出题"
      :visible.sync="isAutoVisible"
      :close-on-click-modal="false"
      width="30%"
      :before-close="handleAddClose2"
    >
      <el-form
        :model="autoForm"
        status-icon
        size="mini"
        ref="autoForm"
        label-width="100px"
      >
        <el-form-item label="试卷名称" prop="name">
          <el-input type="text" v-model="autoForm.name"></el-input>
        </el-form-item>
        <el-form-item label="填空题个数">
          <el-input-number :min="0" v-model="autoForm.blank"></el-input-number>
        </el-form-item>
        <el-form-item label="单选题个数">
          <el-input-number :min="0" v-model="autoForm.single"></el-input-number>
        </el-form-item>
        <el-form-item label="多选题个数">
          <el-input-number :min="0" v-model="autoForm.multi"></el-input-number>
        </el-form-item>
        <el-form-item label="判断题个数">
          <el-input-number :min="0" v-model="autoForm.bool"></el-input-number>
        </el-form-item>
        <el-form-item label="主观题个数">
          <el-input-number :min="0" v-model="autoForm.big"></el-input-number>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isAutoVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAutoForm()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  addPaper,
  getPaper,
  deletePaper,
  updatePaper,
  getQuestion,
  autoPaper,
} from "../service.js";
import { numberToLetter } from "../tools/index";
export default {
  name: "home",
  data() {
    return {
      tableData: [],
      tableDataPaper: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      options: [
        {
          key: "1",
          label: "简单",
        },
        {
          key: "2",
          label: "中等",
        },
        {
          key: "3",
          label: "困难",
        },
      ],
      isAddVisible: false,
      isAutoVisible: false,
      dialogTitle: "",
      addForm: {},
      autoForm: {},
      rules: {
        name: [
          { required: true, message: "试卷名称不能为空", trigger: "blur" },
        ],
      },
      key: ''
    };
  },
  mounted() {
    this.refreshTable();
    getQuestion({
      page: 1,
      pageSize: 10000,
    }).then((res) => {
      this.tableData = res.data.data;
    });
  },
  methods: {
    formatter(row) {
      if (row.selections) {
        let selections = JSON.parse(row.selections);
        let str = "";
        selections.forEach((v, i) => {
          let s = numberToLetter(i);
          str += `${s}:${v.text};`;
        });
        return str;
      }
      return "";
    },
    handleAddClose() {
      this.isAddVisible = false;
    },
    submitForm(formName) {
      if (!this.multipleSelection.length) {
        this.$message.error("请选择试题");
        return;
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let params = JSON.parse(JSON.stringify(this.addForm));
          params.questions = this.multipleSelection.map((v) => v.id).join(",");
          if (this.addForm.id) {
            updatePaper(params.id, params).then((res) => {
              if (res.code == 200) {
                this.$message.success("修改成功");
                this.isAddVisible = false;
                this.refreshTable();
              } else {
                this.$message.error(res.msg[0].msg);
              }
            });
          } else {
            addPaper(params).then((res) => {
              if (res.code == 200) {
                this.$message.success("添加成功");
                this.isAddVisible = false;
                this.refreshTable();
              } else {
                this.$message.error(res.msg[0].msg);
              }
            });
          }
        }
      });
    },
    refreshTable(init = false) {
      if (init) {
        this.currentPage = 1;
      }
      let params = {
        pageSize: this.pageSize,
        page: this.currentPage,
      };
      if (this.key) {
        params.key = this.key
      }
      getPaper(params).then((res) => {
        this.tableDataPaper = res.code === 200 ? res.data.data : [];
        this.total = res.data.total;
      });
    },
    addPaper() {
      this.addForm = {
        name: "",
      };
      this.isAddVisible = true;
      this.multipleSelection = [];
      this.$nextTick(() => {
        this.$refs["addForm"].resetFields();
      });
    },
    deletePaper(row) {
      this.$confirm("此操作将永久删除该记录, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        deletePaper(row.id).then((res) => {
          if (res.code == 200) {
            this.$message.success("删除成功");
            this.refreshTable();
          } else {
            this.$message.error(res.msg);
          }
        });
      });
    },
    updatePaper(row) {
      let questions = row.questions.split(",");
      this.isAddVisible = true;
      this.$nextTick(() => {
        this.multipleSelection = this.tableData.filter((v) =>
          questions.map(Number).includes(v.id)
        );
        this.multipleSelection.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
        this.addForm = JSON.parse(JSON.stringify(row));
      });
    },
    deleteSel(index) {
      this.addForm.selections.splice(index, 1);
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    formatter1(row) {
      return this.formatStr(row.name);
    },
    formatterHard(row) {
      return this.options.find((v) => v.key == row.hard).label;
    },
    formatStr(htmlString) {
      const parser = new DOMParser();
      const doc = parser.parseFromString(htmlString, "text/html");
      // 获取<p>元素
      const pElement = doc.querySelector("p");
      // 提取<p>元素的文本内容
      const textContent = pElement.textContent || pElement.innerText; // 兼容不同浏览器
      return textContent.trim();
    },
    // 自动出题
    addPaperAuto(command) {
      console.log(command);
      this.command = command;
      this.autoForm = {
        name: "",
        blank: "",
        single: "",
        multi: "",
        bool: "",
        big: "",
      };
      this.isAutoVisible = true;
    },
    handleAddClose2() {
      this.isAutoVisible = false;
    },
    submitAutoForm() {
      if (!this.autoForm.name) {
        this.$message.error("试卷名称不能为空");
        return;
      }
      if (
        !this.autoForm.blank &&
        !this.autoForm.single &&
        !this.autoForm.multi &&
        !this.autoForm.bool &&
        !this.autoForm.big
      ) {
        this.$message.error("试题个数不能为空");
        return;
      }
      autoPaper({
        ...this.autoForm,
        command: this.command,
      }).then((res) => {
        if (res.data.code == 200) {
          this.$message.success("新增成功");
          this.refreshTable();
          this.isAutoVisible = false;
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
h2 {
  text-align: center;
  margin-top: 20px;
  margin-bottom: 20px;
}
.consultation-block {
  width: 90%;
  margin-left: 5%;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.edit {
  color: #409eff;
  cursor: pointer;
}
.delete {
  color: #f56c6c;
  cursor: pointer;
}
.row {
  display: flex;
  gap: 20px;
  margin-top: 8px;
}
</style>
